package com.demo.web.core;

import com.demo.core.AnnotationApplicationContext;
import com.demo.project.dao.PersistenceUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Map;

@WebListener

public class DispatcherConfig implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        AnnotationApplicationContext context = new AnnotationApplicationContext("com.demo");
        WebFactory webFactory = context.getWebFactory();
        Map<String, Object> webPathWithBean = webFactory.getWebPathWithBean();
        Map<String, Object> webPathWithMethod = webFactory.getWebPathWithMethod();
        servletContext.setAttribute("webPathWithBean",webPathWithBean);
        servletContext.setAttribute("webPathWithMethod",webPathWithMethod);
        /**
         * 把持久化操作的对象封装进去
         */
        PersistenceUtil persistenceUtil = (PersistenceUtil) context.getBean("persistenceUtil");
        // 进行数据读取操作。
        if (persistenceUtil!=null) {
            System.out.println("应用开始，从存储文件中读取数据！");
            persistenceUtil.readDataFromFiles();
            servletContext.setAttribute("persistenceUtil",persistenceUtil);
            System.out.println("从存储文件中读取数据结束！");
        }


    }

    /**
     * 在本应用中，销毁时 进行持久化操作
     * @param servletContextEvent
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        PersistenceUtil persistenceUtil = (PersistenceUtil) servletContext.getAttribute("persistenceUtil");
        if(persistenceUtil==null){
            System.out.println("-----持久化操作失败-----");
        }else {
            System.out.println("-----持久化操作进行中-----");
            persistenceUtil.writeDataToFiles();
            System.out.println("-----持久化操作完成-----");
        }
        System.out.println("该应用已经销毁！");
    }

}
